//
//  JMForgotPwdTVController.m
//  jiMuOperate
//
//  Created by 胡梅方 on 16/4/23.
//  Copyright © 2016年 jinXinFengLi. All rights reserved.
//

#import "JMForgotPwdTVController.h"
#import "JMCellView.h"
#import "JMTextField.h"
#import "JMResterInfo.h"

@interface JMForgotPwdTVController ()<UITextFieldDelegate>

@end

@implementation JMForgotPwdTVController

{
    UITextField* _userfield;
    UITextField* _newPasswordfield;
    UITextField* _verifield;
    UIButton* verifyBtn;
    NSInteger currentTime;
    NSTimer *timer;
 
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"忘记密码";
    [self setupOther];//创建tableView
    [self createButton];
    
}

-(void)setupOther
{
    self.tableView.scrollEnabled = NO;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
    self.tableView.tableHeaderView = view;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = BACKCOLOR;
    UITapGestureRecognizer *singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapFrom)];
    singleRecognizer.numberOfTapsRequired = 1;
    [self.tableView addGestureRecognizer:singleRecognizer];
    
}
- (void)handleSingleTapFrom
{
    [_userfield resignFirstResponder];
    [_verifield resignFirstResponder];
    [_newPasswordfield resignFirstResponder];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"LoginCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    CGFloat imageH = 40;
    UIImageView *lineImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,50, 320, 1)];
    lineImg.image = [UIImage imageNamed:@"halvingline_2"];
    [cell.contentView addSubview:lineImg];
    lineImg.frame = [ToolViewAndData MyAutoLayout:lineImg];

    UILabel *describLab = [ARC createLabelWithFrame:CGRectMake(10, 5, imageH*2, imageH) Font:15 Text:nil];
    describLab.textColor = [UIColor blackColor];
    describLab.textAlignment = NSTextAlignmentLeft;
    describLab.frame = [ToolViewAndData MyAutoLayout:describLab];
    [cell.contentView addSubview:describLab];
    
    if (indexPath.row == 0) {
 
        describLab.text = @"手机号码";
        if (!_userfield) {
           _userfield = [self addUserFieldWithFrame:CGRectMake(imageH*2, 0, imageH*6, CELLHIGHT)];
            
            [cell.contentView  addSubview:_userfield];
        }
        
        return [JMCellView setupCell:cell HideLine:YES];
    }else if(indexPath.row == 1){
        describLab.text = @"验证码";
        UIButton *verifyB = [[UIButton alloc] initWithFrame:CGRectMake(210, 10,100, imageH-10)];
        verifyBtn = verifyB;
        verifyBtn.clipsToBounds = YES;
        verifyBtn.layer.cornerRadius = 3.f;//设置边角圆弧的半径，
        [verifyBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        verifyBtn.titleLabel.font = [UIFont systemFontOfSize: 12];
        [verifyBtn addTarget:self action:@selector(verifyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [verifyBtn setBackgroundImage:[UIImage imageNamed:@"Send-verification-code"] forState:UIControlStateNormal];
        [verifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        verifyBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        verifyBtn.frame = [ToolViewAndData MyAutoLayout:verifyBtn];
        [cell.contentView addSubview:verifyBtn];
        if (!_verifield) {
            
            _verifield = [self addVeriFieldWithFrame:CGRectMake(80, 0, 180, CELLHIGHT)];
            [cell.contentView  addSubview:_verifield];
        }
    }else if(indexPath.row == 2){
        describLab.text = @"新密码";
        if (!_newPasswordfield) {
            
            _newPasswordfield = [self addNewPasswordFieldWithFrame:CGRectMake(imageH*2, 0, imageH*6, CELLHIGHT)];
            [cell.contentView  addSubview:_newPasswordfield];
        }
 
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CELLHIGHT;
}


- (JMTextField *)addUserFieldWithFrame:(CGRect)frame
{
    //用户名
    JMTextField *textField = [JMTextField createTextFieldWithFrame:frame
                                                              Font:16
                                                       Placeholder:@"输入您注册的手机号码"
                                                   SecureTextEntry:NO
                                                         TextColor:[UIColor blackColor]];
    textField.keyboardType =  UIKeyboardTypePhonePad;
    textField.delegate = self;
    textField.frame =  [ToolViewAndData MyAutoLayout:textField];
    return  textField;
    
}

- (JMTextField *)addVeriFieldWithFrame:(CGRect)frame
{
    JMTextField  *passWord= [JMTextField createTextFieldWithFrame:frame
                                                             Font:16
                                                      Placeholder:@"输入验证码"
                                                  SecureTextEntry:NO
                                                        TextColor:[UIColor blackColor]];
    
    passWord.frame = [ToolViewAndData MyAutoLayout:passWord];
    
    passWord.delegate = self;
    return  passWord;
}
- (JMTextField *)addNewPasswordFieldWithFrame:(CGRect)frame
{
    //密码
    JMTextField  *passWord= [JMTextField createTextFieldWithFrame:frame
                                                             Font:16
                                                      Placeholder:@"6-16个字符，含字母，数字"
                                                  SecureTextEntry:YES
                                                        TextColor:[UIColor blackColor]];
    
    passWord.frame = [ToolViewAndData MyAutoLayout:passWord];
    
    passWord.delegate = self;
    return  passWord;
}


#pragma mark - 创建textField

#pragma mark - 创建登陆注册按钮
- (void)createButton{
    
    CGFloat btnX = 200;
    CGFloat btnH = 40;
    
    
    UIButton* confirmBtn = [ARC createButtonWithFrame:CGRectMake(30,btnX, 260, btnH)
                                             Target:self
                                                  Sel:@selector(confirmBtnClick:)
                                              Title:@"确认登录"];
    
    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"logoin_btn"] forState:UIControlStateNormal];
    confirmBtn.frame = [ToolViewAndData MyAutoLayout:confirmBtn];
    [confirmBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    confirmBtn.tintColor=[UIColor whiteColor];
    [self.view addSubview:confirmBtn];
    
    
}




-(void)verifyBtnClick:(UIButton*)btn
{
    
    if (!_verifield.text&&![ToolViewAndData isMobileNumber:_userfield.text]) {
        SHOWALERT(@"请输入正确的手机号码");
        return;
    }
    
    [self requestVerifyCodeWithPhone:_userfield.text userType:@"findpwd" token:@""];
}
- (void)requestVerifyCodeWithPhone:(NSString *)phone userType:(NSString *)userType token:(NSString *)token
{
    if(!phone.length){
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@?Tel=%@&Type=%@&Token=%@",JMURLVerifyCode,phone,userType,token];
    NSArray *arrayR = @[@"",url,@"GET"];
    [Request startRequestWithArray:arrayR FinishedBlock:^(NSData *data) {
        NSDictionary *dictR = [JMData dictAndTestData:data];
        JMResterInfo *resterInfo = [JMResterInfo objectWithKeyValues:dictR];
        if ([resterInfo.State intValue]>0) {
            currentTime = 60;
            NSString *str = [NSString stringWithFormat:@"%ld秒后重新获取",(long)currentTime];
            
            [verifyBtn setTitle:str forState:UIControlStateNormal];
            
            timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownTime) userInfo:nil repeats:YES];
       
        }else{
            NSString *str = @"重新获取验证码";
            [verifyBtn setTitle:str forState:UIControlStateNormal];
            [timer invalidate];
            SHOWALERT(resterInfo.Msg);
            
        }
        
    } FailBlock:^(NSString *string) {
        //        [timer invalidate];
        SHOWALERT(@"服务器繁忙，请梢后重试");
    }];
    
}
-(void)countDownTime
{
    currentTime--;
    NSString *str = [NSString stringWithFormat:@"%ld秒后重新获取",(long)currentTime];
    
    [verifyBtn setTitle:str forState:UIControlStateNormal];
    verifyBtn.enabled = NO;
    if (currentTime <= 0) {
        [timer invalidate];
        [verifyBtn setTitle: @"获取短信验证码" forState:UIControlStateNormal];
        [verifyBtn setEnabled:YES];
    }
}

-(void)confirmBtnClick:(UIButton*)btn
{
    if (_userfield.text.length*_newPasswordfield.text.length== 0) {
        [MBProgressHUD showError:@"用户名或密码不能为空"];
        return;
    }
    if (!_verifield.text&&![ToolViewAndData isMobileNumber:_userfield.text]) {
        SHOWALERT(@"请输入正确的手机号码");
        return;
    }
    [self TelNo:_userfield.text TelCode:_verifield.text Pwd:_newPasswordfield.text];
}
- (void)TelNo:(NSString *)phone TelCode:(NSString *)telcode Pwd:(NSString *)pwd
{
    
    NSString *urlRe = [NSString stringWithFormat:@"%@",JMURLChangePwd];
    NSDictionary *dictRe = [JMData TelNo:phone TelCode:telcode Pwd:pwd];
    
    NSString *strAry = [JMData stringWithDict:dictRe];
    NSArray *aryRe = @[strAry,urlRe];
    [Request startRequestWithArray:aryRe FinishedBlock:^(NSData *data) {
        NSDictionary *dictR = [JMData dictAndTestData:data];
         JMResterInfo *forgotInfo = [JMResterInfo objectWithKeyValues:dictR];
        if ([forgotInfo.State intValue]>0) {
            SHOWALERT(@"密码修改成功，请重新登录");
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            SHOWALERT(dictR[@"Msg"]);
            
            return ;
        }
        
        
    } FailBlock:^(NSString *string) {
        [MBProgressHUD showError:@"密码修改失败，请梢后重试"];
    }];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    return YES;
    
}


#pragma mark - 禁止屏幕旋转
SHOULDAutorotate(YES)


@end
